from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import subprocess
from fastapi.middleware.cors import CORSMiddleware
import os
import uvicorn

app = FastAPI()
port = int(os.environ.get("FASTAPI_PORT", 8002))
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"]  # 允许所有请求头
)


@app.post("/submit")
async def submit_code(request: Request):
    data = await request.json()
    code = data.get('code', '')
    try:
        # 使用subprocess模块运行Python代码
        result = subprocess.check_output(['python', '-c', code], stderr=subprocess.STDOUT, universal_newlines=True)
        return JSONResponse(content={"message": "代码运行成功", "result": result})
    except subprocess.CalledProcessError as e:
        return JSONResponse(content={"message": "代码运行出错", "error": e.output})


@app.get("/hello")
def read_root():
    return {"Hello": "World"}


